package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.queryobject.QueryObject;
import cn.wolfcode.resultpage.ResultPage;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public int delete(Long id) {

        return employeeMapper.delete(id);
    }

    @Override

    public void insert(Employee employee,Long[] ids) {
        // 密码加密,使用用户名作为加密的"盐"(加密的方式,密码拼接上用户名)
        employee.setPassword(new Md5Hash(employee.getPassword(),employee.getName()).toString());
        // 插入员工表的信息
        employeeMapper.insert(employee);
        if (ids != null && ids.length>0){
            // 处理中间表
            for (Long roleId : ids) {
                // 插入中间表的信息
                employeeMapper.insertRelation(employee.getId(),roleId);
            }

        }
    }

    @Override
    public Employee selectOne(Long id) {
        return employeeMapper.selectOne(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.listAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.update(employee);

        // 先删除原来的中间表数据(一个员工可以有多个角色)会同时删除一个员工对应的多条信息
        employeeMapper.deleteRelation(employee.getId());

        // 添加新的数据
        if (ids != null && ids.length > 0) {
            // 处理中间表
            for (Long roleId : ids) {
                // 插入中间表的信息
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.queryForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        // 使用Spring的StringUtils工具类方法进行判断字符串是否有长度
        if (!StringUtils.hasLength(username)){
            throw new RuntimeException("用户名不能为空");
        }

        if (!StringUtils.hasLength(password)){
            throw new RuntimeException("密码不能为空");
        }
        // 使用sql语句去数据库查询到账号密码信息
        Employee employee = employeeMapper.selectUsernameAndPassword(username, password);
        // 如果用户输错返回给用户提示信息
        if (employee == null){
           throw new RuntimeException("账号和密码不匹配");
        }
        return employee;
    }

    @Override
    public void updatePassword(Long id,String oldPassword, String newPassword) {
        // 获取数据库的数据
        Employee emp = employeeMapper.selectOne(id);
        // 对旧密码进行加盐
        String Md5oldPassword = new Md5Hash(oldPassword,emp.getName()).toString();

        if (!StringUtils.hasLength(newPassword) && !StringUtils.hasLength(oldPassword)){
            throw new RuntimeException("密码不能为空");
        }

        if (emp.getPassword().equals(Md5oldPassword)){
            String Md5newPassword = new Md5Hash(newPassword,emp.getName()).toString();
            employeeMapper.updatePwd(id,Md5newPassword);
        }else {
            throw new RuntimeException("输入密码与原密码不匹配");
        }
    }

    @Override
    public void restPwd(Long id, String newPassword) {
        Employee employee = employeeMapper.selectUser(id);
        String Md5newPassword = new Md5Hash(newPassword, employee.getName()).toString();
        if (newPassword == null){
            throw new RuntimeException("输入密码不能为空");
        }
        if (employee.getPassword().equals(Md5newPassword)){
            throw new RuntimeException("新密码与旧密码重复不能修改,请重新输入");
        }else {
            employeeMapper.updatePwd(id,Md5newPassword);
        }
    }

    @Override
    public void deletes(Long[] ids) {

        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee checkName(String name) {

            return employeeMapper.checkName(name);

    }

    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectById(id);
    }

    @Override
    public HSSFWorkbook exportXls() {
        List<Employee> employees = employeeMapper.listAll();
        // 创建一个excel
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建sheet
        HSSFSheet sheet = workbook.createSheet("员工通讯录");
        // 创建标题行
        HSSFRow row = sheet.createRow(0);
        // 设置标题
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        for (int i = 0;i < employees.size();i++){
            // 获取员工
            Employee employee = employees.get(i);
            // 创建行
            row = sheet.createRow(i+1);
            // 创建单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            if (employee.getAge()!= null){
                row.createCell(2).setCellValue(employee.getAge());
            }
        }
        return workbook;
    }

    @Override
    public void importXls(HSSFWorkbook workbook) {
        // 获取第一页的数据
        HSSFSheet sheet = workbook.getSheetAt(0);
        // 获取最后一行索引
        int lastRowNum = sheet.getLastRowNum();
        // 标题不需要读,索引从1开始
        for (int i = 1;i <= lastRowNum;i++){
            HSSFRow row = sheet.getRow(i);
            Employee employee = new Employee();
            String name = row.getCell(0).getStringCellValue();
            // 如果用户名为空就不再读取数据
            if (!StringUtils.hasLength(name)){
                return;
            }
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());

            HSSFCell cell = row.getCell(2);
            // 根据单元格的类型来调用不同的方法来获取
            if (cell.getCellType().equals(CellType.STRING)){
                // 年龄 按照文本类型的单元格来读取
                String value = cell.getStringCellValue();
                employee.setAge(Integer.valueOf(value));
            }else {
                // 年龄 按照数字类型的单元格来读取
                double value = cell.getNumericCellValue();
                employee.setAge((int)value);
            }
            // 默认密码
            employee.setPassword("1");
            // 调用保存方法
            this.insert(employee,null);
        }
    }

    @Override
    public void updateState(Long id, boolean status) {
        int state = status ? 1 : 0;
        employeeMapper.updateState(id,state);
    }

    @Override
    public List<Employee> selectByRoleSn(String...sns) {

        return employeeMapper.selectByRoleSn(sns);
    }
}
